<template>
    <div class="dynamic-table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleExport" :loading="exportLoading">
          <el-icon><Download /></el-icon> 导出表格
        </el-button>
            <!-- 导出所有数据 -->
    <el-button type="success" @click="handleExportAll" :loading="exportAllLoading">
      <el-icon><Document /></el-icon> 导出全部数据
    </el-button>
        
        <el-button v-if="false" type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
      </div>
      
      <el-form :model="filterForm" ref="filterFormRef" class="filter-form">
        <div class="filter-container">
          <el-form-item 
            v-for="(column, index) in filterColumns" 
            :key="index"
            :label="column.label"
            :prop="column.prop"
            class="filter-item"
          >
            <!-- 文本筛选 -->
            <el-input
              v-if="column.filterType === 'text' || !column.filterType"
              v-model="filterForm[column.prop]"
              :placeholder="`请输入${column.label}`"
              clearable
            />
            
            <!-- 日期筛选 -->
            <el-date-picker
              v-else-if="column.filterType === 'date'"
              v-model="filterForm[column.prop]"
              type="date"
              :placeholder="`请选择${column.label}`"
              value-format="YYYY-MM-DD"
            />
            
            <!-- 下拉筛选 -->
            <el-select
              v-else-if="column.filterType === 'select'"
              v-model="filterForm[column.prop]"
              :placeholder="`请选择${column.label}`"
              clearable
            >
              <el-option
                v-for="option in column.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </div>
        
        <div class="filter-actions">
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon> 筛选
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </div>
      </el-form>
      
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        class="main-table"
      >
        <el-table-column 
          v-for="column in columns" 
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :min-width="column.width || 120"
        />
        
        <el-table-column 
          v-if="false"
          label="操作"
          width="180"
          fixed="right"
        >
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        class="pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, watch } from 'vue'
  import { Download, Plus, Search, Refresh ,Document} from '@element-plus/icons-vue'
  import * as XLSX from 'xlsx'
  
  const props = defineProps({
    // 获取表头数据的API
    columnsApi: Function,
    // 获取表格数据的API
    dataApi: Function,
    // 页面名称
    pageName: String
  })
  
  const columns = ref([])
  const tableData = ref([])
  const filterColumns = ref([])
  const filterForm = ref({})
  const filterFormRef = ref(null)
  const loading = ref(false)
  const exportLoading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  
// ... 其他变量保持不变 ...
const exportAllLoading = ref(false)


// 导出全部数据
const handleExportAll = async () => {
  try {
    exportAllLoading.value = true
    
    // 弹出确认框，因为导出所有数据可能比较耗时
    await ElMessageBox.confirm('确定要导出所有符合条件的数据吗？数据量较大时可能需要一些时间。', '导出确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用后端接口获取所有数据（不带分页参数）
    const allDataResponse = await props.dataApi({
      ...filterForm.value,
      page: 1,
      pageSize: -1 // 使用特殊值表示获取所有数据
    })
    
    // 获取所有数据
    const allData = allDataResponse.list
    
    // 创建导出数据
    const exportData = allData.map(row => {
      const newRow = {}
      columns.value.forEach(col => {
        newRow[col.label] = row[col.prop]
      })
      return newRow
    })
    
    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, props.pageName)
    
    // 导出文件
    XLSX.writeFile(workbook, `${props.pageName}_全部数据_${new Date().toISOString().slice(0, 10)}.xlsx`)
    
    ElMessage.success(`导出成功，共导出 ${exportData.length} 条数据`)
  } catch (error) {
    // 用户取消操作不显示错误
    if (error !== 'cancel') {
      console.error('导出失败:', error)
      ElMessage.error('导出失败: ' + (error.message || '服务器错误'))
    }
  } finally {
    exportAllLoading.value = false
  }
}
  
  // 获取表头数据
  const fetchColumns = async () => {
    try {
      const response = await props.columnsApi()
      columns.value = response.columns
      // 设置筛选列（只包含有筛选类型的列）
      filterColumns.value = response.columns.filter(col => col.filterType)
      // 初始化筛选表单
      filterColumns.value.forEach(col => {
        filterForm.value[col.prop] = ''
      })
    } catch (error) {
      console.error('获取表头失败:', error)
      ElMessage.error('获取表头数据失败')
    }
  }
  
  // 获取表格数据
  const fetchData = async () => {
    loading.value = true
    try {
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        ...filterForm.value
      }
      const response = await props.dataApi(params)
      tableData.value = response.list
      total.value = response.total
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }
  
  // 筛选处理
  const handleFilter = () => {
    currentPage.value = 1
    fetchData()
  }
  
  // 重置筛选
  const resetFilter = () => {
    filterFormRef.value?.resetFields()
    handleFilter()
  }
  
  // 导出表格
  const handleExport = () => {
    exportLoading.value = true
    
    // 创建导出数据
    const exportData = tableData.value.map(row => {
      const newRow = {}
      columns.value.forEach(col => {
        newRow[col.label] = row[col.prop]
      })
      return newRow
    })
    
    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, props.pageName)
    
    // 导出文件
    XLSX.writeFile(workbook, `${props.pageName}_${new Date().toISOString().slice(0, 10)}.xlsx`)
    
    setTimeout(() => {
      exportLoading.value = false
      ElMessage.success('导出成功')
    }, 500)
  }
  
  // 以下为隐藏功能，实际代码保留但功能隐藏
  const handleAdd = () => {
    console.log('新增操作')
  }
  
  const handleEdit = (row) => {
    console.log('编辑操作', row)
  }
  
  const handleDelete = (row) => {
    console.log('删除操作', row)
    ElMessageBox.confirm('确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      ElMessage.success('删除成功')
    })
  }
  
  // 监听页面变化
  watch(() => props.pageName, () => {
    fetchColumns()
    fetchData()
  }, { immediate: true })
  
  onMounted(() => {
    fetchColumns()
    fetchData()
  })
  </script>
  
  <style scoped>
  .dynamic-table-container {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .table-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  
  .filter-form {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .filter-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .filter-item {
    margin-bottom: 0;
    min-width: 200px;
  }
  
  .filter-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
  
  .main-table {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .pagination {
    display: flex;
    justify-content: flex-end;
  }
  </style>
  
<style scoped>
/* 按钮间距调整 */
.table-header .el-button {
  margin-right: 10px;
}
</style>